/*
*  @ 属于哪个服务 urqNodeHttp = 1, borrowMoney = 2, http = 3, nodeHttp = 4, strategyHttp = 5, markeHttp = 6
*/
import axios from 'axios';
import QS from 'qs';
import router from '../router';
import { Notify, Toast } from 'vant';
// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_TYPE === 'production' || process.env.VUE_APP_TYPE === 'test' ? process.env.VUE_APP_SERVER_URL : '/', // 生产与开发区分
  withCredentials: true
});
// request拦截器
service.interceptors.request.use(config => {
  config.headers['token'] = localStorage.getItem('token') || '';
  // 区分上传接口
  if (config.url.indexOf('m/upload') === -1) {
    config.data = QS.stringify(config.data, { allowDots: true });
  }
  return config;
}, error => {
  Promise.reject(error);
});

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非200是抛错strategyHttp
     */
    if (response.data.code === 1001) {
      Toast('登录超时,请重新登录');
      router.push({ path: '/login' });
    }
    if (response.data.code === 0) {
      return response.data;
    } else {
      Toast(response.data.message);
      return response.data;
    }
  },
  error => {
    // console.log(error.response.data);
    if (error.response && error.response.status === 500) {
      Notify({
        message: '无法请求到服务器',
        type: 'danger'
      });
    } else if (error.response && error.response.status === 404) {
      Notify({
        message: '找不到-' + error.response.config.url + '-接口',
        type: 'danger'
      });
    } else {
      Notify({
        message: (error.response && (error.response.data.msg || (error.response && error.response.data.RMsg))) || '无法请求到服务器',
        type: 'danger'
      });
    }
    return Promise.reject(error);
  }
);
export default {
  post: function (options) {
    var data = {
      url: (process.env.VUE_APP_TYPE === 'production' || process.env.VUE_APP_TYPE === 'test' ? '' : '/api') + options.url,
      method: 'post',
      data: options.params,
      timeout: options.timeout || 600000, // 请求超时时间
      onUploadProgress: options.onUploadProgress,
      headers: options.headers || {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      }
    };
    return service(data);
  },
  get: function (options) {
    var data = {
      url: (process.env.VUE_APP_TYPE === 'production' || process.env.VUE_APP_TYPE === 'test' ? '' : '/api') + options.url,
      method: 'get',
      params: options.params,
      timeout: options.timeout || 600000, // 请求超时时间
      headers: options.headers || {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    };
    return service(data);
  }
};
